<%@ page language="java" pageEncoding="UTF-8"%>
<jsp:directive.page import="edu.ntu.im.p2ptrade.P2PTrade"/>
<html>

<head>

<link href="/p2ptrade/css/css.css" rel="stylesheet" type="text/css">

<script type="text/javascript" src="/p2ptrade/js/dialog.js"></script>
<script type="text/javascript" src="/p2ptrade/js/peers.js"></script>
<script type="text/javascript" src="/p2ptrade/js/json.js"></script>
<script type="text/javascript" src="/p2ptrade/js/ajax.js"></script>
<script type="text/javascript" src="/p2ptrade/js/item.js"></script>
<script type="text/javascript" src="/p2ptrade/js/tray.js"></script>
<script type="text/javascript" src="/p2ptrade/js/template.js"></script>
<script type="text/javascript" src="/p2ptrade/js/request.js"></script>
<script type="text/javascript" src="/p2ptrade/js/prototype.js"></script>
<script>
var me = '<%=P2PTrade.getInstance().getPeerName()%>'	
var dialogMgt = new DialogManager();
var peerMgt = new PeerManager("peers");
var peerItemMgt = new ItemManager("peerItem");
var myItemMgt = new ItemManager("myItem");
var trayMgt = new TrayManager("transactionRequest", me);
var reqMgt = new RequestManager();
var whosItem;
var enforceReFresh = false;
var getAll = true;
function updateBackEnd(){
   var req = createAjaxRequest2(function(result){
   		 //alert("update");
          if (result.success){
				if (result.result.currentPeers && result.result.dialogs){
				    currentPeers = result.result.currentPeers;
					var i=0;
					for(var name in currentPeers){
						if(currentPeers[name].name)
						{
					   		dialogMgt.update(currentPeers[name].name, result.result.dialogs[currentPeers[name].name], i);
					   		$(currentPeers[name].name+"_input").peerName=currentPeers[name].name;
					   		i++;
					   	}
					}
					peerMgt.update(result.result.currentPeers);
				}
				if (result.result.peerItems.length>0 || enforceReFresh){
					peerItemMgt.update(result.result.peerItems, "peer");
					//whosItem=null;
				}
				if (result.result.myItems.length>0 ){
				    myItemMgt.update(result.result.myItems, "me");
				}
				// for requests  

				if (result.result.incoming.length>0){
				
					reqMgt.updateIncoming(result.result.incoming);
				}
				
				if (result.result.issued.length>0){
				
					reqMgt.updateIssued(result.result.issued);
				}
				
				if (result.result.denied.length>0){
					reqMgt.updateDenied(result.result.denied);
				}
				if (result.result.aborted.length>0){
					reqMgt.updateAborted(result.result.aborted);
				}
				if (result.result.success.length>0){
					reqMgt.updateSuccess(result.result.success);
				}
				getAll = false;
				enforceReFresh = false;
          }
        });
       
   var url = "/p2ptrade/informFrontEnd.do?getAll="+getAll;

   if (whosItem!= null){
     url+="&whosItem="+whosItem;
   }
   if(document.getElementById("query_user").value != ""){
     url+="&QueryUser="+document.getElementById("query_user").value;
     document.getElementById("query_user").value = "";
   }
  req.open("GET", url , true);
  req.send(null);
}

function sendMsg( msgInput){
   var req = createAjaxRequest2(function(result){
   		//do nothing
		//updateBackEnd();
   });
  req.open("GET", "/p2ptrade/addDialog.do?peer="+msgInput.peerName+"&content="+encodeURI(msgInput.value) , true);
  req.send(null);
}
function lookPeer(peer){
  whosItem = peer;
  var req = createAjaxRequest2(function(result){
   		enforceReFresh = true;
   });
  req.open("GET", "/p2ptrade/refreshPeerItems.do?peer="+whosItem);
  req.send(null);
  $('peerItem').innerHTML = "<span style=\"background-color:red\">Loading...</span>";
  
}

function sendTransactionReq(){
 var items = trayMgt.getItemsInTray();
 var myIds = '';
 var peerIds = '';
 var peer ;
 for (var i=0;i<items.length; i++){
 	if (items[i].ownerId == me){
 	  if (myIds != ''){
 	    myIds += ',';
 	  }
 	  myIds+=items[i].id;
 	}else {
 	   if (peerIds != ''){
 	    peerIds += ',';
 	  }
 	  peerIds+=items[i].id;
 	  peer = items[i].ownerId;
 	}
 }
 var req = createAjaxRequest2(function(result){
      if (result.success){
        $('transactionRequest').innerHTML = "";
      }
   });
  url ='/p2ptrade/sendTrasReq.do?myIds='+myIds+"&peerIds="+peerIds+"&peer="+peer;
  req.open("GET", url);
  req.send(null); 
}

function approveOrDeny(transId, approve){
 var req = createAjaxRequest2(function(result){
   		if (result.sucess){
   		if (approve){
   		  $(transId+"_msg").innerHTML = "Reqest["+transId+"] has been approved, waiting for peer to process!";
   		  }else {
   		  $(transId+"_msg").innerHTML = "Reqest["+transId+"] has been denied";
   		  }

   		}
   });
  url ='/p2ptrade/denyOrApproveRequest.do?transactionId='+transId+"&approve="+approve;
  req.open("GET", url);
  req.send(null); 
  lookPeer(whosItem);
}

function enlargeMe(transId){
 $(transId+'_content').style.display="block";
 $(transId).style.top = "300px";
  $(transId).style.left = "300px";
    $(transId).style.zIndex = "100";
}

function closeMe(transId){
  $(transId+'_content').style.display="none";
  $(transId).style.top =  $(transId).oTop;
  $(transId).style.left = $(transId).oLeft;
  
}




function clearRequest(transactionId, type){
 var req = createAjaxRequest2(function(result){
   		if (result.sucess){
			//$(transactionId).style.display="none";
			location.reload(true);
   		}
   });

  url ='/p2ptrade/consumeRequest.do?transactionId='+transactionId+"&type="+type;
  req.open("GET", url);
  req.send(null); 
}


Event.observe(window, "load", function(){
setTimeout("updateBackEnd()",50);
setInterval("updateBackEnd()", 5000);
});
//updateBackEnd();


</script>


</head>

<body>
<script type="text/javascript" src="js/wz_dragdrop.js"></script>
<div align=center>
<jsp:include page="/top.tpl" />
</div>

<div id="peerItem_title" style="position:absolute;top:80px;left:310px;height:20px;width:500px;z-Index:10;border:1px solid;border-style:dashed; background-color:#C28989;padding:5px"><font color=white>User's Items</font></div>
<div id="peerItem" style="position:absolute;top:110px;left:310px;height:200px;width:500px;z-Index:10;border:1px solid;border-style:dashed; background-color:#ECDBDB;padding:5px"></div>
<div id="myItem_title" style="position:absolute;top:320px;left:310px;height:20px;width:500px;z-Index:10;border:1px solid;border-style:dashed; background-color:#C28989;padding:5px"><font color=white>My Items</font></div>
<div id="myItem" style="position:absolute;top:350px;left:310px;height:200px;width:500px;z-Index:10;border:1px solid;border-style:dashed; background-color:#ECDBDB;padding:5px"></div>
<div id="peers_title" style="position:absolute;top:80px;left:150px;height:20px;width:150px;z-Index:10;border:1px solid;border-style:dashed; background-color:#C28989;padding:5px"><font color=white>User List</font></div>
<div id="peers" style="position:absolute;top:111px;left:150px;height:440px;width:150px;z-Index:10;border:1px solid;border-style:dashed; background-color:#ECDBDB;padding:5px"></div>
<div id="transactionRequest_title" style="position:absolute;top:80px;left:820px;height:20px;width:200px;z-Index:10;border:1px solid;border-style:dashed; background-color:#C28989;padding:5px"><font color=white>Transaction Prepare</font></div>
<div id="transactionRequest" style="position:absolute;left:820px;top:110px;width:200px;height:440px; border:1px solid;overflow:scroll;border-style:dashed; background-color:#ECDBDB;padding:5px"></div>

<textarea id="dialogTemplate" style="display:none">
 <div style="height:20;width:200px;background-color:#BCBCDE;padding-left:5px"> \${peer} </div>

 <br>
 <div style="position:absolute;top:223px;z-Index:10">
  <input type="text" id="\${peer}_input" onkeyup="if(event.keyCode==13)sendMsg(this);" > </input>  
  </div>
</textarea>

<textarea id="dialogContentTemplate" style="display:none">
{for d in dialogs}
  <div style="position:relative;width:170px;height:auto;padding-left:5px">
  \${d.from} to \${d.to} <br>
  \${d.content}
  </div>
{/for}
</textarea>

<textarea id="peerTemplate" style="display:none">
{for p in peers}
  <span style="cursor:pointer" id="\${p.name}_div" onclick="lookPeer('\${p.name}')">  \${p.name}</span>
  {if p.trustable == true}
  <font color="red" face=symbol>&Ouml;</font>
  {/if}
  {if p.trustable == false}
   <font color="red">&times;</font>
  {/if}

  <img src="/p2ptrade/img/UpArrow.gif" onClick="document.getElementById('\${p.name}_detail').style.display = 'none';">

  <img src="/p2ptrade/img/DownArrow.gif" onClick="document.getElementById('\${p.name}_detail').style.display = 'block';"><br>
  <div id="\${p.name}_detail" style="display:none;width:200px;height=200px;background-color:silver">
		<img src="http://\${p.photoURL}" width="50" height="50">　<a href="#" onClick="document.getElementById('query_user').value='\${p.name}';updateBackEnd();">Refresh User Info</a><br>
		Nickanme：\${p.nickName}
	</div>
{/for}
</textarea>

<textarea id="itemTemplate" style="display:none">
<table>
  <tr>
{for i in items}
  
<td>
  <span style="position:absolute; left:\${i.x}" id="_item_\${peer}_\${i.id}">
  <img src="http://\${i.photoUrl}" style="width:100px;height:100px;border:1px solid" ></img> 
  <br>
  
    <div>\${i.name}</div>
    <div>\${i.memo}</div>
    <img src="/p2ptrade/img/mp.gif" onClick="myClick('_item_\${peer}_\${i.id}');"></img>
    </span>
    
</td>
 
{/for}
</tr>
</table>
</textarea>

<textarea id="trayTemplate" style="display:none">
{for i in items}
  <span style="position:absolute; top:\${i.y}px" id="\${i.id}">
  <img src="http://\${i.photoUrl}" style="width:100px;height:100px;border:1px solid" ></img><a href="javascript:trayMgt.removeItemFromTray('\${i.id}', '\${i.ownerId }');" >[X]</a> <br>
  
    <div>\${i.name}</div>
    <div>\${i.memo}</div>
    <div>\${i.ownerId}</div>
    </span>
{/for}
{if canReq == true}
 <div style="position:absolute;top:95%">
  <a href="javascript:sendTransactionReq();">Send Transaction Request</a>
  </div>
{/if}

</textarea>
<!-- for requests  -->
<textarea id="requestTemplate" style="display:none">
	<div style="width:350px;height:auto;border:1px solid; background-color:#FFFFA6">
	<div style="width:349px;height:20px;border:1px solid; background-color:\${titlecolor }">\${title } <a href="javascript:enlargeMe('\${t.trans.id }')">[+]</a> <a href="javascript:closeMe('\${t.trans.id }')">[-]</a></div>
	<div style="width:350px;height:230px;display:none" id="\${t.trans.id}_content">
	<table>
	 <tr>
	   {for i in t.trans.part1.items}
	    <td>
	     <div style="position:relative;background-color:#D9D9D9">
			   <img src="http://\${i.photoUrl}" style="width:100px;height:100px;border:1px solid" ></img> <br>
			    <div>\${i.name}</div>
			    <div>\${i.memo}</div>
			    <div>\${i.ownerId}</div>
	    </div>
	    </td>
	   {/for}
	   {for i in t.trans.part2.items}
	   <td>
	     <div style="position:relative;background-color:#BFBFBF">
			   <img src="http://\${i.photoUrl}" style="width:100px;height:100px;border:1px solid" ></img><br>
			    <div>\${i.name}</div>
			    <div>\${i.memo}</div>
			    <div>\${i.ownerId}</div>
	    </div>
	    </td>
	   {/for}
	   </tr>
	  </table>
	  <div id="\${t.trans.id}_msg"> 
	   {if type=='incoming'}
	   <a href="javascript:approveOrDeny('\${t.trans.id}', true);">approve</span></a>&nbsp;  <a href="javascript:approveOrDeny('\${ t.trans.id}', false);">deny</a>
	   {/if}
	   {if type=='issued'}
	    Request has sent, waiting for peer to process!
	   {/if}
	   {if type=='denied'}
	   Request has been denied by peer! <a href="javascript:clearRequest('\${t.trans.id}', '\${type}');">[clear]</span>
	   {/if}
	   {if type=='aborted'}
        Request has been aborted due to failure obtaining lock !<a href="javascript:clearRequest('\${t.trans.id}', '\${type}');">[clear]</span>
	   {/if}
	   {if type=='success'}
	   success <a href="javascript:clearRequest('\${t.trans.id}', '\${type}');">[clear]</span>
	   {/if}
	   </div>
	  </div>
	</div>	
</textarea>
<input type="hidden" id="query_user" name="query_user" value="">
</body>
</html>
<script>
SET_DHTML(CURSOR_MOVE);
var trayIndex = 0;
var originalPos = new Object();
function my_PickFunc(){
	if(dd.obj.id.search(/_dialog/)>=0){
		var input_element = document.getElementById(dd.obj.id.substring(8)+"_input");
		input_element.focus();
	}
}

function my_DropFunc(){
  if (dd.obj.id.indexOf("_item")>=0){
	var pos = findElementPosition($("transactionRequest"), null, false);
	var strwidth = $("transactionRequest").style.width;
	var strheight = $("transactionRequest").style.height;
	var width = parseInt(strwidth.substring(0, strwidth.indexOf("px")));
	var height = parseInt(strheight.substring(0, strheight.indexOf("px")));
	var item;
	if (peerItemMgt.getItem(dd.obj.id)!=null){
		  item = peerItemMgt.getItem(dd.obj.id);
	}else {
		  item = myItemMgt.getItem(dd.obj.id);
	}
	if (dd.obj.x >= pos.x && dd.obj.x <= pos.x + width && dd.obj.y >= pos.y && dd.obj.y <= pos.y + height )
	{
		trayMgt.addItemToTray(item);
	}
	dd.obj.moveTo(item.pixx, item.pixy);
	}
}
function findElementPosition(element, targetParentId, debug) {
	var curleft = curtop = 0;
	if (element.offsetParent) {
		curleft = element.offsetLeft;
		curtop = element.offsetTop;
		if (debug) confirm(element.offsetLeft);
		while (element = element.offsetParent) {
			if (targetParentId && element.id && element.id == targetParentId) {
				break;
		}
		if (debug) confirm(element.offsetLeft);
			curleft += element.offsetLeft;
			curtop += element.offsetTop;
		}
	}
	return {x: curleft, y: curtop};
}

function myClick(id){
	var item;
	if (peerItemMgt.getItem(id)!=null){
		  item = peerItemMgt.getItem(id);
	}else {
		  item = myItemMgt.getItem(id);
	}
	trayMgt.addItemToTray(item);
}

</script>



